const http = require('http');
const app = require('./app');
const { sequelize } = require('./models');
const SocketService = require('./sockets/chat');

const PORT = process.env.API_PORT || 3303;

// 创建HTTP服务器
const server = http.createServer(app);

// 初始化Socket服务
const socketService = new SocketService(server);
app.set('socketService', socketService); // 使socketService在app中可用

// 数据库连接和启动服务器
sequelize.sync({ alter: true })
  .then(() => {
    server.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
      console.log(`WebSocket available at ws://localhost:${PORT}`);
    });
  })
  .catch(err => {
    console.error('Database connection error:', err);
    process.exit(1);
  });